#!/bin/bash
# (c) 2014, Hagai Kariti <hkariti@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

function usage {
    echo "Usage: $0 PLAYBOOK [ -i inventory ] [--VAR VALUE [...]] [ -- ANSIBLE-PLAYBOK_ARGS ]"
}

function get_arg {
    opt=$1
    shift
    [ $# = 0 ] && return 1
    echo $1
}

function args_error {
    echo "Option $1 requires an argument" >&2
    exit 1
}

if [ $# = 0 ]; then
    usage
    exit 0
fi

playbook=$1
playbook_dir=`dirname "$playbook"`
inventory="ansible_exec_dummy,"
ansible_playbook=ansible-playbook
conf_files=(~/.ansible-exec.conf /etc/ansible/ansible-exec.conf)
ansible_args=()

for c in "${conf_files[@]}"; do
    if [ -f "$c" ]; then
        source "$c"
        [ -n "$ANSIBLE_PLAYBOOK_ARGS" ] && ansible_args+=("${ANSIBLE_PLAYBOOK_ARGS[@]}")
        [ -n "$DEFAULT_INVENTORY" ] && inventory=$DEFAULT_INVENTORY
        break
    fi
done
shift
while [ -n "$1" ]; do
    case "$1" in
        --)
            shift
            ansible_args+=("$@")
            break
            ;;
        -i)
            inventory=`get_arg "$@"` || args_error $1
            shift
            ;;
        -e)
            var=`get_arg "$@"` || args_error $1
            var=${2%%=*}
            value=${2#*=}
            ansible_args+=(-e "$var=\"$value\"")
            shift
            ;;
        --*)
            var=${1#--}
            if echo $var | grep -q =; then
                value=${var#*=}
                var=${var%%=*}
            else
                value=`get_arg "$@"` || args_error $1
                shift
            fi

            # Support var_name being passed as --var-name
            var=${var//-/_}
            ansible_args+=(-e "$var=\"$value\"")
            ;;
        *)
            echo "$0: Invalid argument: $1" >&2
            usage >&2
            exit 2
            ;;
    esac
    shift
done

exec $ansible_playbook -i "$playbook_dir/$inventory" "$playbook" "${ansible_args[@]}"
